package cn.piggy.service;

import cn.piggy.util.TokenStorageUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import java.io.IOException;

public abstract class BaseExecutorService {
    private final OkHttpClient okHttpClient;
    protected final ObjectMapper objectMapper;

    public BaseExecutorService(OkHttpClient okHttpClient){
        this.okHttpClient = okHttpClient;
        this.objectMapper = new ObjectMapper();
        this.objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    public abstract String queryToken() throws IOException;

    public String getToken() throws IOException {
        String key = this.getClass().getSimpleName() + "#Token";
        String token = TokenStorageUtil.tokens.get(key);
        if(token==null){
            synchronized (this.getClass()){
                token = TokenStorageUtil.tokens.get(key);
                if(token==null){
                    token = queryToken();
                    TokenStorageUtil.tokens.put(key, token);
                }
            }
        }
        return token;
    }

    public <T> Request getRequestObject(String host, T object) throws IOException {
        String json = objectMapper.writeValueAsString(object);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody requestBody = RequestBody.create(json, mediaType);
        String token = getToken();
        return new Request.Builder()
                .url(host +"?access_token=" + token)
                .method("POST", requestBody)
                .build();
    }

    public String executeHttpRequest(Request request) throws IOException {
        Response response = okHttpClient.newCall(request).execute();
        ResponseBody body = response.body();
        if(body!=null){
            return body.string();
        }
        return null;
    }

    public String executeHttpRequest(String host, Object object) throws IOException {
        Request request = getRequestObject(host, object);
        return executeHttpRequest(request);
    }

    public String requestToken(Request request) throws IOException {
        Response execute = okHttpClient.newCall(request).execute();
        ResponseBody body = execute.body();
        if(body!=null){
            String string = body.string();
            JSONObject jsonObject = JSONObject.parseObject(string);
            return jsonObject.getString("access_token");
        }
        throw new RuntimeException();
    }

}
